package com.yicong.ants.viewmodel

import com.cchao.simplelib.core.PrefHelper
import com.yicong.ants.manager.ad.AdManager
import com.yicong.ants.manager.config.ZzConfigs

/**
 *启动页ViewModel
 */
object AppStartViewModel {
    /**
     * SP中存放隐私协议同意状态的KEY
     */
    const val KEY_PRIVACY_AGREED = "confirm_app"

    /**
     * 隐私协议同意状态观察者
     */
    private var privacyAgreeStateObserver: ((Boolean) -> Unit)? = null

    /**
     * 广告显示状态观察者
     */
    private var adStateObserver: ((AdManager.State) -> Unit)? = null

    /**
     * 开屏页背景数据观察者
     */
    private var splashImagesObserver: ((List<String>?) -> Unit)? = null

    /**
     * 广告显示状态
     */
    @JvmStatic
    var adState: AdManager.State? = null
        set(value) {
            if (value == null)
                return
            field = value
            // 设置状态的同时通知观察者
            adStateObserver?.invoke(value)
        }

    /**
     * 注册隐私协议同意状态观察者
     */
    fun observePrivacyAgreeState(observer: (Boolean) -> Unit) {
        this.privacyAgreeStateObserver = observer
    }

    /**
     * 同意隐私协议
     */
    fun agreePrivacy() {
        PrefHelper.putInt(KEY_PRIVACY_AGREED, getPrivacyAgreeKey())
        this.privacyAgreeStateObserver?.invoke(true)
    }

    /**
     * 注册广告显示状态观察者
     */
    fun observeAdState(observer: (AdManager.State) -> Unit) {
        this.adStateObserver = observer
    }

    /**
     * 注册开屏页背景数据观察者
     */
    fun observeSplashImages(observer: (List<String>?) -> Unit) {
        this.splashImagesObserver = observer
    }

    /**
     * 启动数据加载
     */
    fun start() {
        ZzConfigs.init()// 启动图需要初始化才能获取到
        var version = -1
        try {
            version = PrefHelper.getInt(KEY_PRIVACY_AGREED, -1)
        } catch (e: Exception) {
            PrefHelper.remove(KEY_PRIVACY_AGREED)
        }
        privacyAgreeStateObserver?.invoke(getPrivacyAgreeKey() == version)
        this.splashImagesObserver?.invoke(ZzConfigs.mIndexInfo?.splash)
    }

    private fun getPrivacyAgreeKey(): Int {
        return ZzConfigs.getClientConf().getWebUrl("ant_privacy").version
    }
}